package com.wingy.psyduckplayer.Activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;


import com.wingy.psyduckplayer.Data.Music;
import com.wingy.psyduckplayer.Data.MusicList;
import com.wingy.psyduckplayer.R;
import com.wingy.psyduckplayer.model.PropertyBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {

    private static final int PERMISSION_REQUESTCODE = 1;

    // 显示组件
    private ImageButton imgBtn_Previous;
    private ImageButton imgBtn_PlayOrPause;
    private ImageButton imgBtn_Stop;
    private ImageButton imgBtn_Next;
    private ListView list;
    private DrawerLayout drawerLayout;
    private NavigationView navigationView;
    private Toolbar toolbar;

    //歌曲列表对象
    private ArrayList<Music> musicArrayList;

    // 当前歌曲的序号，下标从0开始
    private int number = 0;

    //播放状态
    private int status;

    //广播接收器
    private StatusChangedReceiver receiver;
    private RelativeLayout root_Layout;
    private TextView text_Current;
    private TextView text_Duration;
    private SeekBar seekBar;
    private TextView textView;
    private Handler seekBarHandler;
    //当前歌曲的持续时间和当前位置，用作进度条
    private int duration;
    private int time;
    //进度条控制常量
    private static final int PROGRESS_INCREASE = 0;
    private static final int PROGRESS_PAUSE = 1;
    private static final int PROGRESS_RESET = 2;
    //播放模式常量
    private static final int MODE_LIST_SEQUENCE = 0;
    private static final int MODE_SINGLE_CYCLE = 1;
    private static final int MODE_LIST_CYCLE = 2;
    private static final int MODE_RANDOM = 3;
    private int playmode;
    //退出判定
    private static boolean isExit = false;
    //
    private ImageView imageView_sleep;
    private Timer timer_sleep;
    private static final boolean NOTSLEEP = false;
    private static final boolean ISSLEEP = true;
    //
    private int sleepminute = 30;
    //
    private static boolean sleepmode;

    private GestureDetector gestureDetector;
    private static boolean changeable = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.drawer_layout_main);

        gestureDetector = new GestureDetector(this, this);
        changeable = true;
        findViews();
        setSupportActionBar(toolbar);
        registerListeners();
        time = 0;
        duration = 0;
        if (checkPermissions(new String[]{
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        })) {
            initMusicList();
            initListView();
            checkMusicfile();
            //绑定广播接收器，可以接收广播
            bindStatusChangedReceiver();
            initSeekBarHandler();
            startService(new Intent(this, MusicService.class));
            status = MusicService.COMMAND_STOP;
            playmode = MainActivity.MODE_LIST_SEQUENCE;
            sleepmode = MainActivity.NOTSLEEP;

        }
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onDown(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return gestureDetector.onTouchEvent(event);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (gestureDetector.onTouchEvent(ev))
            ev.setAction(MotionEvent.ACTION_CANCEL);
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        if (e1.getX() > (getResources().getDisplayMetrics().widthPixels - 50)
                && e1.getX() - e2.getX() > 150
                && changeable
                && !drawerLayout.isDrawerOpen(GravityCompat.START)) {
            startActivity(new Intent(MainActivity.this, LrcActivity.class));
            overridePendingTransition(R.anim.to_left_enter, R.anim.to_left_exit);
        }
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        sendBroadcastOnCommand(MusicService.COMMAND_CHECK_IS_PLAYING);
        PropertyBean propertyBean = new PropertyBean(MainActivity.this);
        String theme = propertyBean.getTheme();
        setTheme(theme);
        setPlayMode(propertyBean.getPlaymode());
        if (sleepmode == MainActivity.ISSLEEP) imageView_sleep.setVisibility(View.VISIBLE);
        else imageView_sleep.setVisibility(View.INVISIBLE);
    }


    @Override
    protected void onDestroy() {
        if (status == MusicService.STATUS_STOPPED) {
            stopService(new Intent(this, MusicService.class));
        }
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if (drawerLayout.isDrawerOpen(GravityCompat.START))
            drawerLayout.closeDrawer(GravityCompat.START);

        else if (!drawerLayout.isDrawerOpen(GravityCompat.START)) {
            Timer timer = null;
            if (!isExit) {
                isExit = true;
                Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        isExit = false;
                    }
                }, 2000);
            } else sendBroadcast(new Intent("CLOSE"));
        } else super.onBackPressed();
    }

    /**
     * 设置主题
     */
    private void setTheme(String theme) {
        if ("彩色".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_color);
        } else if ("花朵".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_digit_flower);
        } else if ("群山".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_mountain);
        } else if ("小狗".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_running_dog);
        } else if ("冰雪".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_snow);
        } else if ("女孩".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_music_girl);
        } else if ("朦胧".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_blur);
        }
    }

    /**
     * 设置播放模式
     */
    private void setPlayMode(String playMode) {
        if ("顺序播放".equals(playMode)) {
            playmode = MainActivity.MODE_LIST_SEQUENCE;
        } else if ("单曲循环".equals(playMode)) {
            playmode = MainActivity.MODE_SINGLE_CYCLE;
        } else if ("列表循环".equals(playMode)) {
            playmode = MainActivity.MODE_LIST_CYCLE;
        } else if ("随机播放".equals(playMode)) {
            playmode = MainActivity.MODE_RANDOM;
        }
    }

    /**
     * 绑定广播接收器
     */
    private void bindStatusChangedReceiver() {
        receiver = new StatusChangedReceiver();
        IntentFilter filter = new IntentFilter(MusicService.BROADCAST_MUSICSERVICE_UPDATE_STATUS);
        registerReceiver(receiver, filter);
    }

    /**
     * 检查权限
     */
    private boolean checkPermissions(String[] permissions) {
        boolean allGranted = true;
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                //有一项没授权
                allGranted = false;
                break;
            }
        }
        if (allGranted) {
            //已经授权
            return true;

        } else {
            //没有授权
            ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUESTCODE);
            return false;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean isAllGranted = true;
        // 判断是否所有的权限都已经授予了
        for (int grant : grantResults) {
            if (grant != PackageManager.PERMISSION_GRANTED) {
                isAllGranted = false;
                break;
            }
        }

        if (isAllGranted) {
            initMusicList();
            initListView();
            checkMusicfile();
            //绑定广播接收器，可以接收广播
            bindStatusChangedReceiver();
            initSeekBarHandler();
            startService(new Intent(this, MusicService.class));
            status = MusicService.COMMAND_STOP;
            //默认顺序播放模式
            playmode = MainActivity.MODE_LIST_SEQUENCE;
            sleepmode = MainActivity.NOTSLEEP;
        } else {
            new AlertDialog.Builder(MainActivity.this)
                    .setMessage("需要开启权限才能正常使用")
                    .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //引导用户到设置中去进行设置
                            Intent intent = new Intent();
                            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                            intent.setData(Uri.fromParts("package", getPackageName(), null));
                            startActivity(intent);
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Toast.makeText(MainActivity.this, "权限被拒绝无法使用", Toast.LENGTH_SHORT).show();
                            MainActivity.this.onDestroy();
                        }
                    })
                    .create()
                    .show();
        }
    }

    /**
     * 获取显示组件
     */
    private void findViews() {
        imgBtn_Previous = (ImageButton) findViewById(R.id.imageButton1);
        imgBtn_PlayOrPause = (ImageButton) findViewById(R.id.imageButton2);
        imgBtn_Stop = (ImageButton) findViewById(R.id.imageButton3);
        imgBtn_Next = (ImageButton) findViewById(R.id.imageButton4);
        list = (ListView) findViewById(R.id.listView1);
        root_Layout = (RelativeLayout) findViewById(R.id.relativeLayout1);
        text_Current = (TextView) findViewById(R.id.textView);
        text_Current.setText("--:--");
        text_Duration = (TextView) findViewById(R.id.textView2);
        textView = (TextView) findViewById(R.id.textView5);
        seekBar = (SeekBar) findViewById(R.id.seekBar);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        navigationView = (NavigationView) findViewById(R.id.nav_view);
        imageView_sleep = (ImageView) findViewById(R.id.imageView_sleep);
    }

    /**
     * 初始化音乐列表对象
     */
    private void initMusicList() {
        musicArrayList = MusicList.getMusicList();
        //避免重复添加音乐
        if (musicArrayList.isEmpty()) {
            Cursor mMusicCursor = this.getContentResolver().query(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                    new String[]{
                            MediaStore.Audio.Media.TITLE,
                            MediaStore.Audio.Media.DURATION,
                            MediaStore.Audio.Media.ALBUM,
                            MediaStore.Audio.Media.ARTIST,
                            MediaStore.Audio.Media._ID,
                            MediaStore.Audio.Media.DATA,
                            MediaStore.Audio.Media.DISPLAY_NAME}, null, null,
                    MediaStore.Audio.AudioColumns.TITLE);

            //标题
            int indexTitle = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE);
            //艺术家
            int indexArtist = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST);
            //总时长
            int indexTotalTime = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION);
            //路径
            int indexPath = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);

            /**通过mMusicCursor游标遍历数据库，并将Music类对象加载带ArrayList中*/
            for (mMusicCursor.moveToFirst(); !mMusicCursor.isAfterLast(); mMusicCursor
                    .moveToNext()) {
                String strTitle = mMusicCursor.getString(indexTitle);
                String strArtist = mMusicCursor.getString(indexArtist);
                String strTotoalTime = mMusicCursor.getString(indexTotalTime);
                String strPath = mMusicCursor.getString(indexPath);

                if (strArtist.equals("<unknown>"))
                    strArtist = "无艺术家";
                Music music = new Music(strTitle, strArtist, strPath, strTotoalTime);
                musicArrayList.add(music);
            }
        }
    }

    /**
     * 设置适配器并初始化listView
     */
    private void initListView() {
        List<Map<String, String>> list_map = new ArrayList<Map<String, String>>();
        HashMap<String, String> map;
        SimpleAdapter simpleAdapter;
        for (Music music : musicArrayList) {
            map = new HashMap<String, String>();
            map.put("musicName", music.getmusicName());
            map.put("musicArtist", music.getmusicArtist());
            list_map.add(map);
        }

        String[] from = new String[]{"musicName", "musicArtist"};
        int[] to = {R.id.listview_tv_title_item, R.id.listview_tv_artist_item};

        simpleAdapter = new SimpleAdapter(this, list_map, R.layout.listview, from, to);
        list.setAdapter(simpleAdapter);
    }

    /**
     * 如果列表没有歌曲，则播放按钮不可用，并提醒用户
     */
    private void checkMusicfile() {
        if (musicArrayList.isEmpty()) {
            imgBtn_Next.setEnabled(false);
            imgBtn_PlayOrPause.setEnabled(false);
            imgBtn_Previous.setEnabled(false);
            imgBtn_Stop.setEnabled(false);
            Toast.makeText(getApplicationContext(), "当前没有歌曲文件", Toast.LENGTH_SHORT).show();
        } else {
            imgBtn_Next.setEnabled(true);
            imgBtn_PlayOrPause.setEnabled(true);
            imgBtn_Previous.setEnabled(true);
            imgBtn_Stop.setEnabled(true);
        }
    }

    // 媒体播放类
    private MediaPlayer player = new MediaPlayer();

    /**
     * 为显示组件注册监听器
     */
    private void registerListeners() {

        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_theme:
                        new AlertDialog.Builder(MainActivity.this)
                                .setTitle("请选择主题")
                                .setItems(R.array.theme, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        String theme = PropertyBean.THEMES[which];
                                        MainActivity.this.setTheme(theme);
                                        PropertyBean propertyBean = new PropertyBean(MainActivity.this);
                                        propertyBean.setAndSaveTheme(theme);
                                    }
                                }).show();
                        break;
                    case R.id.menu_playmode:
                        String[] mode = new String[]{"顺序播放", "单曲循环", "列表循环", "随机播放"};

                        new AlertDialog.Builder(MainActivity.this)
                                .setTitle("播放模式")
                                .setSingleChoiceItems(mode, playmode, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        playmode = which;
                                        String playMode = PropertyBean.PLAYMODE[which];
                                        PropertyBean propertyBean = new PropertyBean(MainActivity.this);
                                        propertyBean.setAndSavePlaymode(playMode);
                                    }
                                })
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        switch (playmode) {
                                            case 0:
                                                playmode = MainActivity.MODE_LIST_SEQUENCE;
                                                Toast.makeText(getApplicationContext(), R.string.sequence, Toast.LENGTH_SHORT).show();
                                                break;
                                            case 1:
                                                playmode = MainActivity.MODE_SINGLE_CYCLE;
                                                Toast.makeText(getApplicationContext(), R.string.singlecycle, Toast.LENGTH_SHORT).show();
                                                break;
                                            case 2:
                                                playmode = MainActivity.MODE_LIST_CYCLE;
                                                Toast.makeText(getApplicationContext(), R.string.listcycle, Toast.LENGTH_SHORT).show();
                                                break;
                                            case 3:
                                                playmode = MainActivity.MODE_RANDOM;
                                                Toast.makeText(getApplicationContext(), R.string.random, Toast.LENGTH_SHORT).show();
                                                break;
                                        }
                                    }
                                }).show();
                        break;
                    case R.id.menu_sleep:
                        showSleepDialog();
                        break;
                    case R.id.menu_lrc:
                        startActivity(new Intent(MainActivity.this, LrcActivity.class));
                        break;
                    case R.id.menu_about:
                        new AlertDialog.Builder(MainActivity.this)
                                .setTitle("可达鸭音乐播放器")
                                .setMessage(R.string.about2).show();
                        break;
                    case R.id.menu_quit:
                        new AlertDialog.Builder(MainActivity.this)
                                .setTitle("提示")
                                .setMessage(R.string.quit_message).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                System.exit(0);
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        }).show();
                        break;
                }
                drawerLayout.closeDrawer(GravityCompat.START);
                return true;
            }
        });

        imgBtn_Previous.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (playmode) {
                    case MainActivity.MODE_RANDOM:
                        sendBroadcastOnCommand(MusicService.COMMAND_RANDOM_PREVIOUS);
                        break;
                    default:
                        sendBroadcastOnCommand(MusicService.COMMAND_PREVIOUS);
                        break;
                }
            }
        });
        imgBtn_PlayOrPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (status) {
                    case MusicService.STATUS_PLAYING:
                        sendBroadcastOnCommand(MusicService.COMMAND_PAUSE);
                        break;
                    case MusicService.STATUS_PAUSED:
                        sendBroadcastOnCommand(MusicService.COMMAND_RESUME);
                        break;
                    case MusicService.STATUS_STOPPED:
                        switch (playmode) {
                            case MODE_RANDOM:
                                sendBroadcastOnCommand(MusicService.COMMAND_RANDOM);
                                break;
                            default:
                                sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                                break;
                        }
                        break;
                    default:
                        break;
                }
            }
        });
        imgBtn_Stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendBroadcastOnCommand(MusicService.COMMAND_STOP);
            }
        });
        imgBtn_Next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (playmode) {
                    case MainActivity.MODE_RANDOM:
                        sendBroadcastOnCommand(MusicService.COMMAND_RANDOM_NEXT);
                        break;
                    default:
                        sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                        break;
                }
            }
        });

        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                number = position;
                sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
            }
        });
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                //跟随变化
                if (text_Current.getText() != "--:--")
                    text_Current.setText(formatTime(seekBar.getProgress()));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                changeable = false;
                //暂停移动
                seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                changeable = true;
                if (status != MusicService.STATUS_STOPPED) {
                    time = seekBar.getProgress();
                    //更新文本
                    text_Current.setText(formatTime(time));
                    //发送广播执行跳转
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                }
                if (status == MusicService.STATUS_PLAYING) {
                    //发送广播执行跳转
                    //sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                    //恢复移动
                    seekBarHandler.sendEmptyMessage(PROGRESS_INCREASE);
                }
                if (status == MusicService.STATUS_PAUSED) {
                    //恢复移动
                    sendBroadcastOnCommand(MusicService.COMMAND_RESUME);
                    seekBarHandler.sendEmptyMessage(PROGRESS_INCREASE);
                }
            }
        });
    }

    /***/
    private void showSleepDialog() {
        final View userview = this.getLayoutInflater().inflate(R.layout.dialog, null);
        final TextView textView_minute = (TextView) userview.findViewById(R.id.dialog_tv);
        final Switch aSwitch = (Switch) userview.findViewById(R.id.dialog_switch);
        final SeekBar seekBar = (SeekBar) userview.findViewById(R.id.dialog_seekBar);

        textView_minute.setText("睡眠于：" + sleepminute + "分钟");
        if (sleepmode == MainActivity.ISSLEEP) aSwitch.setChecked(true);
        seekBar.setMax(60);
        seekBar.setProgress(sleepminute);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                sleepminute = progress;
                textView_minute.setText("睡眠于：" + sleepminute + "分钟");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                sleepmode = isChecked;
            }
        });

        final TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                System.exit(0);
            }
        };

        final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle("选择睡眠时间（0~60分钟）");
        dialog.setView(userview);
        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog.setNeutralButton("重置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (sleepmode == MainActivity.ISSLEEP) {
                    timerTask.cancel();
                    timer_sleep.cancel();
                }
                sleepmode = MainActivity.NOTSLEEP;
                sleepminute = 30;
                imageView_sleep.setVisibility(View.INVISIBLE);
            }
        });
        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (sleepmode == MainActivity.ISSLEEP) {
                    timer_sleep = new Timer();
                    int time = seekBar.getProgress();
                    timer_sleep.schedule(timerTask, time * 60 * 1000);
                    imageView_sleep.setVisibility(View.VISIBLE);
                } else {
                    timerTask.cancel();
                    if (timer_sleep != null) timer_sleep.cancel();
                    dialog.dismiss();
                    imageView_sleep.setVisibility(View.INVISIBLE);
                }
            }
        });
        dialog.show();
    }


    /**
     * 发送命令，控制音乐播放
     */
    private void sendBroadcastOnCommand(int command) {
        Intent intent = new Intent(MusicService.BROADCAST_MUSICSERVICE_CONTROL);
        intent.putExtra("command", command);
        //根据不同命令，封装不同的数据
        switch (command) {
            case MusicService.COMMAND_PLAY:
                intent.putExtra("number", number);
                break;
            case MusicService.COMMAND_SEEK_TO:
                intent.putExtra("time", time);
                break;
            case MusicService.COMMAND_PREVIOUS:
            case MusicService.COMMAND_NEXT:
            case MusicService.COMMAND_PAUSE:
            case MusicService.COMMAND_RESUME:
            case MusicService.COMMAND_STOP:
            default:
                break;
        }
        sendBroadcast(intent);
    }

    private String formatTime(int msec) {
        int minute = msec / 1000 / 60;
        int second = msec / 1000 % 60;
        String minuteString;
        String secondString;
        if (minute < 10) {
            minuteString = "0" + minute;
        } else {
            minuteString = "" + minute;
        }
        if (second < 10) {
            secondString = "0" + second;
        } else {
            secondString = "" + second;
        }
        return minuteString + ":" + secondString;
    }

    private void initSeekBarHandler() {
        seekBarHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case PROGRESS_INCREASE:
                        if (seekBar.getProgress() < duration) {
                            //前进一秒
                            seekBar.setProgress(time);
                            //seekBar.incrementProgressBy(1000);
                            seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                            //修改当前显示进度文本
                            text_Current.setText(formatTime(time));
                            time += 1000;
                        }
                        break;
                    case PROGRESS_PAUSE:
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        break;
                    case PROGRESS_RESET:
                        //重置进度条画面
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        seekBar.setProgress(0);
                        if (text_Current.getText() != "--:--")
                            text_Current.setText("00:00");
                        break;
                }
            }
        };
    }

    /**
     * 状态接收器
     */
    class StatusChangedReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            String musicName = intent.getStringExtra("musicName");
            String musicArtist = intent.getStringExtra("musicArtist");

            status = intent.getIntExtra("status", -1);
            switch (status) {
                case MusicService.STATUS_PLAYING:
                    seekBarHandler.removeMessages(PROGRESS_INCREASE);
                    time = intent.getIntExtra("time", 0);
                    duration = intent.getIntExtra("duration", 0);
                    number = intent.getIntExtra("number", number);
                    list.setSelection(number);
                    seekBar.setProgress(time);
                    seekBar.setMax(duration);
                    seekBarHandler.sendEmptyMessage(PROGRESS_INCREASE);
                    text_Current.setText(formatTime(time));
                    text_Duration.setText(formatTime(duration));
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.pause);
                    textView.setText(musicName + "-" + musicArtist);
                    break;
                case MusicService.STATUS_PAUSED:
                    seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);
                    textView.setText(musicName + "-" + musicArtist);
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.play);
                    break;
                case MusicService.STATUS_STOPPED:
                    time = 0;
                    duration = 0;
                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    textView.setText("");
                    text_Current.setText("--:--");
                    text_Duration.setText("--:--");
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.play);
                    break;
                case MusicService.STATUS_COMPLETED:
                    number = intent.getIntExtra("number", 0);

                    if (playmode == MainActivity.MODE_LIST_SEQUENCE) {
                        if (number == MusicList.getMusicList().size() - 1)
                            sendBroadcastOnCommand(MusicService.COMMAND_STOP);
                        else
                            sendBroadcastOnCommand(MusicService.COMMAND_NEXT);

                    } else if (playmode == MainActivity.MODE_SINGLE_CYCLE) {
                        sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                    } else if (playmode == MainActivity.MODE_LIST_CYCLE) {
                        if (number == MusicList.getMusicList().size() - 1) {
                            number = 0;
                            sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                        } else sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                    } else if (playmode == MainActivity.MODE_RANDOM) {
                        sendBroadcastOnCommand(MusicService.COMMAND_RANDOM);
                    }

                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    textView.setText("");
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.play);
                    break;
                default:
                    break;
            }
        }
    }

}
